﻿using AutoMapper;
using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Role;
using System.Transactions;
using Microsoft.Extensions.Logging;
using RBAC.Domain.RBAC;

namespace RBAC.Write.Api.Application.Handler.Role
{
    public class UpdateRoleHandler : IRequestHandler<UpdateRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly IBaseRepository<RolePermissionModel> rolePermissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateRoleHandler> logger;

        public UpdateRoleHandler(IBaseRepository<RoleModel> roleRepository, IBaseRepository<RolePermissionModel> rolePermissionRepository, IMapper mapper, ILogger<UpdateRoleHandler> logger)
        {
            this.roleRepository = roleRepository;
            this.rolePermissionRepository = rolePermissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        
        /// <summary>
        /// 更新角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            
            try
            {
                logger.LogInformation("开始更新角色，角色ID: {RoleId}", request.Id);
                
                // 使用Dapper查询角色
                var role = roleRepository.GetFirstOrDefault("Id = @Id", new { Id = request.Id });
                if (role == null)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "角色不存在";
                    logger.LogWarning("角色不存在，ID: {RoleId}", request.Id);
                    return Task.FromResult(res);
                }
                
                logger.LogInformation("找到角色: {RoleName} (ID: {RoleId})", role.RoleName, role.Id);
                
                using (TransactionScope tran = new TransactionScope())
                {
                    try
                    {
                        // 1. 软删除现有的角色权限关联
                        var existingRolePermissions = rolePermissionRepository.GetAll("RoleId = @RoleId AND IsDeleted = false", new { RoleId = request.Id });
                        logger.LogInformation("找到 {PermissionCount} 个现有权限关联", existingRolePermissions.Count);
                        
                        foreach (var rolePermission in existingRolePermissions)
                        {
                            rolePermission.IsDeleted = true;
                            var updateResult = rolePermissionRepository.Update(rolePermission);
                            logger.LogInformation("软删除权限关联: RoleId={RoleId}, PermissionId={PermissionId}, 结果={Result}", 
                                rolePermission.RoleId, rolePermission.PermissionId, updateResult);
                        }
                        
                        // 2. 更新角色基本信息
                        var updatedRole = mapper.Map(request, role);
                        updatedRole.CreateTime = role.CreateTime; // 保持原始创建时间
                        updatedRole.IsDeleted = false;
                        
                        var roleUpdateResult = roleRepository.Update(updatedRole);
                        logger.LogInformation("角色基本信息更新结果: {Result}", roleUpdateResult);
                        
                        // 3. 创建新的角色权限关联
                        if (request.PermissionIds != null && request.PermissionIds.Any())
                        {
                            logger.LogInformation("开始创建新的权限关联，权限数量: {PermissionCount}", request.PermissionIds.Count());
                            
                            foreach (var permissionId in request.PermissionIds)
                            {
                                var newRolePermission = new RolePermissionModel()
                                {
                                    RoleId = request.Id,
                                    PermissionId = permissionId,
                                    IsDeleted = false,
                                    CreateTime = DateTime.Now
                                };
                                
                                var createResult = rolePermissionRepository.Create(newRolePermission);
                                logger.LogInformation("创建权限关联: RoleId={RoleId}, PermissionId={PermissionId}, 结果={Result}", 
                                    request.Id, permissionId, createResult);
                            }
                        }
                        else
                        {
                            logger.LogInformation("没有指定权限ID，跳过权限关联创建");
                        }
                        
                        tran.Complete();
                        
                        res.Data = roleUpdateResult;
                        res.Code = APIEnums.Success;
                        res.Msg = "角色更新成功";
                        
                        logger.LogInformation("角色 {RoleName} (ID: {RoleId}) 更新完成", updatedRole.RoleName, updatedRole.Id);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "更新角色过程中发生错误: {Message}", ex.Message);
                        res.Code = APIEnums.Error;
                        res.Msg = "更新角色失败";
                        res.Data = 0;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新角色失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "更新角色失败";
                res.Data = 0;
            }

            return Task.FromResult(res);
        }
    }
}
